from flask import Blueprint,render_template,g,request,jsonify
from models.user.User import User
from models.log.NormalLog import NormalLog
from Service import Pagination,UserService
from app import db
from sqlalchemy import or_


route_account = Blueprint('account_page',__name__ )

@route_account.route("/index")
def index():
    current_user = g.current_user
    page_num = int(request.args.get("page",1))

    # 搜索
    status = int(request.args.get("status",-1))
    search = request.args.get("search","")
    # 保存搜索状态
    condition = {
        "status": status,
        "search": search
    }

    query = User.query
    if status > -1 and search == "":
        query = query.filter_by(status=status)
    if status == -1 and search != "":
        query = query.filter(or_(User.nickname.contains(search),User.mobile.contains(search)))
    if status > -1 and search != "":
        query = query.filter(User.status == status,or_(User.nickname.contains(search),User.mobile.contains(search)))

    # 分页
    totals = query.count()
    pagination = Pagination(page_num, totals)

    # if page_num == pagination["max_page"]:
    #     data_list = query.offset(pagination["offset"]).limit(totals-pagination["offset"]).all()

    if totals != 0:
        data_list = query.offset(pagination["offset"]).limit(pagination["page_size"]).all()
    else:
        data_list = []
    pagination["data_list"] = data_list

    return render_template("account/index.html",current_user=current_user,pagination=pagination,condition=condition)


@route_account.route("/info")
def info():
    current_user = g.current_user
    id = int(request.args.get("id"))
    user = User.query.get(id)
    if user is None:
        return render_template("error/error.html")
    log_list = NormalLog.query.filter_by(uid=id).order_by(NormalLog.id.desc()).limit(10).all()

    return render_template("account/info.html",current_user=current_user,user=user,log_list=log_list)


@route_account.route("/insert",methods=["GET","POST"])
def insert():
    current_user = g.current_user
    if request.method == "GET":
        return render_template("account/insert.html",current_user=current_user)

    req_dict = request.values

    if User.query.filter_by(login_name=req_dict["login_name"]).first():
        return jsonify({"code":-1,"msg":"账号已注册！"})

    user = User()
    user.nickname = req_dict["nickname"]
    if req_dict["sex"] == "男":
        user.sex = 1
    else:
        user.sex = 0
    user.mobile = req_dict["mobile"]
    user.email = req_dict["email"]
    user.login_name = req_dict["login_name"]
    user.login_salt = UserService.geneSalt()
    user.login_pwd = UserService.genePwd(req_dict["login_pwd"],user.login_salt)
    user.created_time = UserService.geneTime()
    user.updated_time = UserService.geneTime()
    try:
        db.session.add(user)
        db.session.commit()
    except:
        return jsonify({"code":-1,"msg":"添加失败！"})

    return jsonify({"code":200,"msg":"添加成功！"})


@route_account.route("/edit",methods=["GET","POST"])
def edit():
    current_user = g.current_user
    if request.method == "GET":
        id = request.args.get("id")
        user = User.query.get(id)
        if user is None:
            return render_template("error/error.html")
        return render_template("/account/edit.html",current_user=current_user,user=user)

    req_dict = request.values
    user = User.query.get(req_dict["id"])

    if user is None:
        return render_template("error/error.html")

    user.nickname = req_dict["nickname"]
    if req_dict["sex"] == "男":
        user.sex = 1
    else:
        user.sex = 0
    user.mobile = req_dict["mobile"]
    user.email = req_dict["email"]

    if req_dict["login_pwd"] != "":
        if len(req_dict["login_pwd"]) < 6 or len(req_dict["login_pwd"]) >16 :
            return jsonify({"code": -1, "msg": "请输入6-16位密码！"})
        else:
            user.login_pwd = UserService.genePwd(req_dict["login_pwd"], user.login_salt)

    user.updated_time = UserService.geneTime()

    try:
        db.session.add(user)
        db.session.commit()
    except:
        return jsonify({"code": -1, "msg": "修改失败！"})

    return jsonify({"code": 200, "msg": "修改成功！"})


@route_account.route("/remove",methods=["POST"])
def remove():
    try:
        id = request.form.get("id")
        User.query.filter_by(uid=id).update({"status": 0})
        db.session.commit()
    except:
        return jsonify({"code":-1,"msg":"删除失败！"})

    return jsonify({"code":200,"msg":"删除成功！"})


@route_account.route("/recover",methods=["POST"])
def recover():
    try:
        id = request.form.get("id")
        User.query.filter_by(uid=id).update({"status": 1})
        db.session.commit()
    except:
        return jsonify({"code":-1,"msg":"恢复失败！"})

    return jsonify({"code":200,"msg":"恢复成功！"})